#!/use/bin/python
# coding=utf-8
# 早间开机 数据分析-夜间音量-推送成功率
import datetime
import pymysql

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql):
    conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num

#根据月份 获取本月指定指标的 总和
#tableName 指定的报表
#columnName 指定的指标字段
#date 月份
def getSumNumByTableColumnNameAndDate(tableName,columnName,date):
    conn, cur = getDataConnection()
    selectNumSql = f"""
                     select sum({columnName}) from {tableName} t where 1=1   
                     """;
    if len(date) >0:
        selectNumSql = f"""{selectNumSql} and SUBSTR( t.ref_date, 1,7) = '{date}' and LENGTH(t.ref_date) = 10  """
    cur.execute(selectNumSql)
    #print(selectNumSql);
    numResult = cur.fetchone()
    num = 0
    if numResult!= None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

# 记录 数据分析-夜间音量-推送成功率 analysis_yjyl_complete_rate
def insertYjylCompleteRate(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_yjyl_complete_rate 表是否已经存在当天 数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_yjyl_complete_rate t where 1=1  and t.ref_date =  '{date}'")
        # 获取当日可以执行夜间音量的设备量
        nightNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'narvPre' ")
        # 获取当日夜间音量推送次数
        newPushNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'narvExecute' ")
        #计算 当天用户当前音量比经验值小的次数
        minNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'narvFail'  and JSON_EXTRACT(t.msg,'$.reason') = 'current volume less than pre' ")
        # 计算 当天成功降低音量的次数
        successNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'narvComplete' ")
        # 计算夜间音量成功率
        successRate = getRateByXY(successNum,newPushNum)
        # 准备执行夜间音量恢复次数
        recoverNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'darvExecute' '")
        # 夜间音量恢复成功次数
        recoverSuccessNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'darvComplete' ")

        if countNum == 0:
            logDetail =f"{date}日新增-夜间音量可以执行夜间音量的设备量为{nightNum},推送次数为{newPushNum}" \
                       f"\n用户比当前音量经验值少的数量为{minNum},成功降低音量的次数为{successNum},成功率为{successRate},准备执行夜间音量恢复次数{recoverNum},夜间音量恢复成功次数为{recoverSuccessNum}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_yjyl_complete_rate(night_num,auto_num,min_num,success_num,success_rate,recover_num,recover_success_num,ref_date) 
                value({nightNum},{newPushNum},{minNum},{successNum},{successRate},{recoverNum},{recoverSuccessNum},'{date}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{date}日更新-夜间音量可以执行夜间音量的设备量为{nightNum},推送次数为{newPushNum}," \
                        f"\n用户比当前音量经验值少的数量为{minNum},成功降低音量的次数为{successNum},成功率为{successRate},准备执行夜间音量恢复次数{recoverNum},夜间音量恢复成功次数为{recoverSuccessNum}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_yjyl_complete_rate set night_num = {nightNum} , auto_num = {newPushNum} ,min_num = {minNum},
                success_num = {successNum},success_rate = {successRate} ,recover_num = {recoverNum},recover_success_num = {recoverSuccessNum},update_time = now()  where ref_date = '{date}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-夜间音量-推送成功率 analysis_yjyl_complete_rate - 月度
def insertYjylCompleteRateMonth(toMonthDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_yjyl_complete_rate 表是否已经存在当月 数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_yjyl_complete_rate t where 1=1  and t.ref_date =  '{toMonthDay}'")
        # 获取当日可以执行夜间音量的设备量
        nightNum = getSumNumByTableColumnNameAndDate('analysis_yjyl_complete_rate', 'night_num', toMonthDay)
        # 获取当月夜间夜间音量 执行次数
        newPushNum = getSumNumByTableColumnNameAndDate('analysis_yjyl_complete_rate', 'auto_num', toMonthDay)
        #计算 当月用户当前音量比经验值小的次数
        minNum = getSumNumByTableColumnNameAndDate('analysis_yjyl_complete_rate', 'min_num', toMonthDay)
        # 计算 成功降低音量的次数
        successNum = getSumNumByTableColumnNameAndDate('analysis_yjyl_complete_rate', 'success_num', toMonthDay)
        # 计算夜间音量成功率
        successRate = getRateByXY(successNum, newPushNum)
        # 准备执行夜间音量恢复次数
        recoverNum = getSumNumByTableColumnNameAndDate('analysis_yjyl_complete_rate', 'recover_num', toMonthDay)
        # 夜间音量恢复成功次数
        recoverSuccessNum = getSumNumByTableColumnNameAndDate('analysis_yjyl_complete_rate', 'recover_success_num', toMonthDay)
        if countNum == 0:
            logDetail = f"{toMonthDay}月新增-夜间音量可以执行夜间音量的设备量为{nightNum},推送次数为{newPushNum}," \
                        f"\n用户比当前音量经验值少的数量为{minNum},成功降低音量的次数为{successNum},成功率为{successRate},准备执行夜间音量恢复次数{recoverNum},夜间音量恢复成功次数为{recoverSuccessNum}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_yjyl_complete_rate(night_num,auto_num,min_num,success_num,success_rate,recover_num,recover_success_num,ref_date) 
                value({nightNum},{newPushNum},{minNum},{successNum},{successRate},{recoverNum},{recoverSuccessNum},'{toMonthDay}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{toMonthDay}月更新-夜间音量可以执行夜间音量的设备量为{nightNum},推送次数为{newPushNum}," \
                        f"\n用户比当前音量经验值少的数量为{minNum},成功降低音量的次数为{successNum},成功率为{successRate},准备执行夜间音量恢复次数{recoverNum},夜间音量恢复成功次数为{recoverSuccessNum}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_yjyl_complete_rate set night_num = {nightNum} , auto_num = {newPushNum} ,min_num = {minNum},
                success_num = {successNum},success_rate = {successRate} ,recover_num={recoverNum},recover_success_num = {recoverSuccessNum},update_time = now()  where ref_date = '{toMonthDay}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 50
        jobName = '	核心指标-夜间音量-推送成功率'
        tableName = 'analysis_yjyl_complete_rate'
        # 插入日志表
        saveLogSql = f"""insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                                                value({jobId},'{jobName}','{detail}','{tableName}','{ref_date}')"""
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    date = getdate(d)
    yyMMddDate = getdateyyMMdd(d)
    monthdate = getMonthdate(d)
    print (f"{date}日期,更新<数据分析-夜间音量-服务推送成功率>报表")
    insertYjylCompleteRate(date)
    insertYjylCompleteRateMonth(monthdate)

